<?php

namespace Caifenglei\AuthRbac\Http\Controllers;

use Caifenglei\AuthRbac\Http\Actions\RoleAction;
use Caifenglei\AuthRbac\Http\Requests\CreateRoleRequest;
use Caifenglei\AuthRbac\Models\Role;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\Permission\Exceptions\PermissionDoesNotExist;
use Spatie\Permission\Exceptions\RoleAlreadyExists;

class RoleController extends Controller
{
    /**
     * 角色列表
     * @param Request $request
     */
    public function index(Request $request): JsonResponse
    {
        $keyword  = $request->input('keyword', '');
        $status   = $request->input('status', '');
        $pageSize = $request->input('page_size', 15);

        $query = Role::withCount(['permissions' => function($query) {
            $query->orderBy('sort');
        }, 'users'])->orderBy('sort');
        if($keyword){
            $query->where('name', 'like', "%{$keyword}%")->orWhere('label', 'like', "%{$keyword}%");
        }
        if($status) {
            $query->where('status', $status);
        }

        $roles = $query->paginate($pageSize);
        return $this->success('所有角色', $this->formatPaginate($roles));
    }

    /**
     * 新增角色
     */
    public function store(CreateRoleRequest $request) {
        $validated = $request->validated();
        try {
            $role = RoleAction::createRole($validated);
            return $this->success('已成功添加角色', ['id' => $role->getKey()]);
        }catch (RoleAlreadyExists $e) {
            return $this->fail('角色已存在，请重新命名');
        }catch (PermissionDoesNotExist $e) {
            return $this->fail('分配给角色的权限不存在');
        }
    }

    public function destroy(Request $request) {
        $ids = $request->input('ids', []);
        if(count($ids) === 0){
            return $this->fail('请选择要删除的角色');
        }
        $roles = Role::withCount('users')->whereIn('id', $ids)->get();
        if(count($roles) !== count($ids)) {
            return $this->fail('选择的角色不存在');
        }
        try{
            $deleted_role_ids = RoleAction::deleteRoles($roles);
            return $this->success('角色删除成功', $deleted_role_ids);
        }catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 更新角色
     */
    public function update(CreateRoleRequest $request, $id) {
        $validated = $request->validated();
        $role = Role::find($id);
        if (!$role) {
            return $this->fail('更新失败，角色不存在');
        }
        try {
            RoleAction::updateRole($role, $validated);
        }catch (PermissionDoesNotExist $e){
            return $this->fail('分配给角色的权限不存在');
        }
        return $this->success('角色更新成功');
    }

    public function show($id) {
        $role = RoleAction::getRoleInfo($id);
        if (!$role) {
            return $this->fail('角色不存在');
        }
        return $this->success('角色详情', $role->toArray());
    }
}
